package com.attilax.lang.xml;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

public class AutoXML {
	
	private List<String> fruit = new ArrayList<String>();
	//初始化即将显示的在xml中的元素...
	public void initList(){
		fruit.add("草莓");
		fruit.add("橘子");
		fruit.add("香蕉");
		fruit.add("葡萄");
	} 
	
	public void BuildXML(){
	
		initList();
		//创建根节点...
		Element root = new Element("水果");
		//将根节点添加到文档中...
		Document Doc  = new Document(root);
		for(int i = 0; i < fruit.size(); i++){
			//创建各种类水果的节点...
			Element elements = new Element(fruit.get(i));
			//给各种水果节点加子节点...比如价格...
			elements.addContent(new Element("价格").setText(i*10+"元"));
			root.addContent(elements);
			
			XMLOutputter XMLOut = new XMLOutputter(FormatXML());
			try {
				XMLOut.output(Doc, new FileOutputStream("E:\\语言学习\\fruit.xml"));
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		
	}
	
	public Format FormatXML(){
		//格式化生成的xml文件，如果不进行格式化的话，生成的xml文件将会是很长的一行...
		Format format = Format.getCompactFormat();
		format.setEncoding("utf-8");
		format.setIndent(" ");
		return format;
	}
	
	public static void main(String[] args){
		try{
			AutoXML mXml = new AutoXML();
			System.out.println("生成xml文件.....");
			mXml.BuildXML();
		}catch(Exception e){
			e.printStackTrace();
		}
	}

}
